home *** CD-ROM | disk | FTP | other *** search
Wrap
Imports System.Globalization Imports System.IO Imports Microsoft.Win32 Module MainModule Sub Main() ' Run one of the Textxxxx procedures below by uncommenting only one statement 'TestStringsAreObjects() 'TestBoxing() 'TestBoxing2() 'TestStringFunctions() 'TestForEachOnStrings() 'TestStringOptimizations() 'TestCompareOrdinal() 'TestCultureInfo() 'TestFormatNumbers() 'TestFormatDates() 'TestFormatToString() 'TestIFormattable() 'TestIFormatProvider() 'TestIFormatProvider2() 'TestChar() 'TestStringBuilder() 'TestStringBuilderVsStrings() 'TestNumberClasses() 'TestNumberFormatting() 'TestNumberParsing() 'TestConvertClass() 'TestBase64Conversions() 'TestRandom() 'TestDateTime() 'TestDateFormats() 'TestDateParsing() 'TestTimeZone() 'TestGuid() 'TestEnum() 'TestEnumFlags() ' These statements are usuful when running inside Visual Studio.NET Console.WriteLine("") Console.WriteLine(">>> write Enter to terminate the program <<<") Console.ReadLine() End Sub ' This procedure test the reference type nature of the String class. Sub TestStringsAreObjects() Dim s1 As String = "ABCD" Dim s2 As String = s1 ' Prove that both variables point to the same object, therefore strings are reference types. Console.WriteLine(s1 Is s2) ' => True End Sub ' This procedure benchmarks calls to empty routines, one requiring boxing and the other one ' not requiring it Sub TestBoxing() Dim i As Integer Dim start As Date Dim res As Integer ' benchmark the version that does NOT use boxing start = Now For i = 1 To 10000000 res = GetInteger(i) Next Console.WriteLine("Without boxing: " & Now.Subtract(start).ToString) ' benchmark the version that uses boxing and unboxing start = Now For i = 1 To 10000000 res = CInt(GetObject(i)) Next Console.WriteLine("With boxing: " & Now.Subtract(start).ToString) End Sub ' support procedures for TestBoxing Function GetInteger(ByVal n As Integer) As Integer Return n End Function Function GetObject(ByVal o As Object) As Object Return o End Function ' test code optimized for boxing Sub TestBoxing2() Dim i, j As Integer Dim start As Date ' The version that does NOT cache the value type in a reference variable. start = Now For i = 1 To 1000 For j = 1 To 100000 GetObject2(i, j) Next Next Console.WriteLine("Non-optimized: " & Now.Subtract(start).ToString) ' The version that caches the value type in a reference variable. start = Now For i = 1 To 1000 ' Cache the value type in an Object variable. Dim o As Object = i For j = 1 To 100000 GetObject2(o, j) Next Next Console.WriteLine("Optimized: " & Now.Subtract(start).ToString) End Sub Function GetObject2(ByVal o As Object, ByVal o2 As Object) As Object Return o End Function ' this procedure tests several string functions Sub TestStringFunctions() ' A sequence of <N> characters û similar to VB6 String() function. ' (Note the c suffix to "A" as a Char rather than a string.) Dim s As New String("A"c, 10) Console.WriteLine(s) ' => AAAAAAAAAA 'Another way to get the same result.x s = New String(CChar("A"), 10) Console.WriteLine(s) ' => AAAAAAAAAA s = "ABCDEFGHIJ" Console.WriteLine(s.Length) ' => 10 ' Note that index is always zero-based. Console.WriteLine(s.Chars(3)) ' => D s = "ABCDEFGHIJ" ' The VB6 way of inserting a substring after 3rd character. s = Left(s, 3) & "1234" & Mid(s, 4) ' The VB.NET object-oriented way to perform the same operation. s = s.Insert(3, "1234") Console.WriteLine(s) ' => ABC1234DEFGHIJ ' trim leading/trailing spaces and tab chars from a string. s = " A sentence to be trimmed " Dim cArr() As Char = {" "c, Chr(9)} s = s.TrimStart(cArr) Console.WriteLine("'" & s & "'") ' => 'a sentence to be trimmed' ' check whether a string begins with a given character sequence If s.StartsWith("abc") Then Console.WriteLine("The string begins with 'abc'") Else Console.WriteLine("The string doesn't begin with 'abc'") End If ' pad to the right with zeroes s = "12345" s = s.PadRight(10, "0"c) Console.WriteLine(s) ' => 1234500000 ' >>>>>> This code proves that the CompareTo method works in strange ways s = "aaa" Console.WriteLine(s.CompareTo("AAA")) ' => -1 Console.WriteLine(s.CompareTo("ZZZ")) ' => -1 Console.WriteLine(s.CompareTo("aaz")) ' => -1 ?????? Console.WriteLine(s.CompareTo("000")) ' => 1 ?????? ' use the string enumerator s = "ABCDE" Dim c As Char For Each c In s Console.Write(c & ".") ' => A.B.C.D.E. Next ' the Concat shared method Console.Write(String.Concat("ABC ", "DEF ", "GHI")) ' => ABC DEF GHI ' Compare two strings in case insensitive mode. Dim s1 As String = "A" Dim s2 As String = "z" Select Case String.Compare(s1, s2, True) Case 0 : Console.WriteLine("s1 = s2") Case 1 : Console.WriteLine("s1 > s2") Case -1 : Console.WriteLine("s1 < s2") End Select End Sub ' this procedure tests For Each on a string Sub TestForEachOnStrings() Dim start As Date Dim i As Integer Dim s As New String("*"c, 1000000) Dim c, ch As Char start = Now For Each c In s ch = c Next Console.WriteLine("For Each: {0} secs.", Now.Subtract(start)) start = Now For i = 0 To s.Length - 1 ch = s.Chars(i) Next Console.WriteLine("For + Chars method: {0} secs.", Now.Subtract(start)) End Sub ' this procedure tests various string optimization techniques Sub TestStringOptimizations() Dim s1 As String Dim s2 As String ' prove that the compiler can optimize string allocation s1 = "1234" & "5678" s2 = "12345678" Console.WriteLine(s1 Is s2) ' => True ' Attempt to modify the S1 string Mid(s1, 2, 1) = "x" ' prove that a new string was created behind the scenes Console.WriteLine(s1 Is s2) ' => False ' Prove that the compiler isn't always able to detect same strings. s1 = "1234" s1 &= "5678" s2 = "12345678" Console.WriteLine(s1 Is s2) ' => False ' similar code, but this time ' explicitly ask the runtime to look for a string match in the intern pool. s1 = "ABCD" s1 = String.Intern(s1 & "EFGH") s2 = String.Intern("ABCDEFGH") Console.WriteLine(s1 Is s2) ' => True End Sub ' this procedure tests the CompareOrdinal method Sub TestCompareOrdinal() Dim start As Date Dim i As Integer Dim res As Integer start = Now For i = 1 To 10000000 res = String.CompareOrdinal("one", "ONE") Next Console.WriteLine("CompareOrdinal: {0} secs.", Now.Subtract(start)) start = Now For i = 1 To 10000000 res = String.Compare("one", "ONE") Next Console.WriteLine("Compare: {0} secs.", Now.Subtract(start)) start = Now TestOptionCompareBinary(1000000) Console.WriteLine("Option Compare Binary: {0} secs.", Now.Subtract(start)) start = Now TestOptionCompareText(1000000) Console.WriteLine("Option Compare Text: {0} secs.", Now.Subtract(start)) End Sub ' support routine for testing binary comparisons Sub TestOptionCompareBinary(ByVal times As Integer) Dim i As Integer Dim res As Boolean For i = 1 To times res = ("1111" >= CStr(i)) Next End Sub ' this procedure test the CultureInfo object Sub TestCultureInfo() ' Get information about the current locale. Dim ci As CultureInfo = CultureInfo.CurrentCulture ' Assuming that the current language is Italian, we get: Console.WriteLine(ci.Name) ' => it Console.WriteLine(ci.EnglishName) ' => Italian Console.WriteLine(ci.NativeName) ' => italiano Console.WriteLine(ci.LCID) ' => 16 Console.WriteLine(ci.TwoLetterISOLanguageName) ' => it Console.WriteLine(ci.ThreeLetterISOLanguageName) ' => ita Console.WriteLine(ci.ThreeLetterWindowsLanguageName) ' => ITA ' get additional info through the TextInfo object Dim ti As TextInfo = ci.TextInfo Console.WriteLine(ti.ANSICodePage) ' => 1252 Console.WriteLine(ti.EBCDICCodePage) ' => 20280 Console.WriteLine(ti.OEMCodePage) ' => 850 Console.WriteLine(ti.ListSeparator) ' => ; ' How do you spell "Sunday" in German? ' First, create a CultureInfo for German. Dim ciDe As New CultureInfo("de-DE") ' Next, get the corresponding DateTimeFormatInfo object. Dim dtfi As DateTimeFormatInfo = ciDe.DateTimeFormat '' Here's the answer. Console.WriteLine(dtfi.GetDayName(DayOfWeek.Sunday)) ' => Sonntag ' Get info on all the installed cultures. Dim ciArr() As CultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures) ' Print abbreviation and English name of each culture. Dim c As CultureInfo For Each c In ciArr Console.WriteLine(c.Name & " (" & c.EnglishName & ")") Next ' Compare these two strings in case insensitive mode ' according to rules of Italian language. Dim s1 As String = "cioΦ" Dim s2 As String = "CIO╚" ' You can create a CultureInfo on the fly. If String.Compare(s1, s2, True, New CultureInfo("it")) = 0 Then Console.WriteLine("s1 = s2") End If End Sub ' this procedure tests formatting number options Sub TestFormatNumbers() Dim msg As String ' Print the value of a string variable. Dim xyz As String = "foobar" msg = String.Format("The value of {0} variable is {1}", "XYZ", xyz) Console.WriteLine(msg) ' => The value of XYZ variable is foobar ' Format a Currency according to current locale. msg = String.Format("Total is {0:C}, balance is {1:C}", 123.45, -67) Console.WriteLine(msg) ' => Total is $123.45, balance is ($67.00) ' The Number format uses the thousand separator character msg = String.Format("Total is {0:N}", 123456.78) Console.WriteLine(msg) ' => Total is 123,456.78 ' You can append an integer after the "N" character to round ' or extend the number of digits after the decimal point: msg = String.Format("Total is {0:N4}", 123456.785555) Console.WriteLine(msg) ' => Total is 123,456.7856 ' the Decimal format works with integers only msg = String.Format("Total is {0:D8}", 123456) Console.WriteLine(msg) ' => Total is 00123456 'The fixed-point format is useful with decimal values, ' and you can specify how many decimal digits should be displayed (2 if no length is provided): msg = String.Format("Total is {0:F3}", 123.45678) Console.WriteLine(msg) ' => Total is 123.457 'The scientific (or exponential) format displays numbers as n.nnnnE+eeee ' and you can control how many digital digits are used in the mantissa portion: msg = String.Format("Total is {0:E}", 123456.789) Console.WriteLine(msg) ' => Total is 1.234568E+005 msg = String.Format("Total is {0:E3}", 123456.789) Console.WriteLine(msg) ' => Total is 1.235E+005 'The General format converts to either fixed-point or exponential format, ' depending on which format delivers the most compact result: msg = String.Format("Total is {0:G}", 123456) Console.WriteLine(msg) ' => Total is 123456 msg = String.Format("Total is {0:G4}", 123456) Console.WriteLine(msg) ' => Total is 1235E+05 ' the X format converts numbers to hexadecimal strings; ' if you specify a length, the number is padded with leading zeroes if necessary: msg = String.Format("Total is {0:X8}", 65535) Console.WriteLine(msg) ' => Total is 0000FFFF ' The Percent format msg = String.Format("Percentage is {0:P}", 0.123) Console.WriteLine(msg) ' => Percentage is 12.30 % ' The RoundTrip format converts numbers to a string without omitting any prevcision loss msg = String.Format("Value of PI is {0:R}", Math.PI) Console.WriteLine(msg) ' => Value of PI is 3.1415926535897931 ' examples of custom formats for numbers msg = String.Format("Total is {0:##,###.00}", 1234.567) Console.WriteLine(msg) ' => Total is 1,234.57 msg = String.Format("Percentage is {0:##.000%}", 0.3456) Console.WriteLine(msg) ' => Percentage is 34.560% ' An example of prescaler msg = String.Format("Length in {0:###,.00 }", 12344) Console.WriteLine(msg) ' => Total is 12.34 ' Two examples of exponential format msg = String.Format("Total is {0:#.#####E+00}", 1234567) Console.WriteLine(msg) ' => Total is 1.23457E+06 msg = String.Format("Total is {0:#.#####E0}", 1234567) Console.WriteLine(msg) ' => Total is 1.23457E6 ' Two examples with separate sections msg = String.Format("Total is {0:##;<##>}", -123) Console.WriteLine(msg) ' => Total is <123> msg = String.Format("Total is {0:#;(#);zero}", -1234567) Console.WriteLine(msg) ' => Total is (1234567) Dim N1 As Integer = 1234 Dim N2 As Integer = 4566 msg = String.Format("N1 is {0:greater than;less than;equal to} N2", N1 - N2) Console.WriteLine(msg) ' => N1 is less than N1 End Sub ' this procedure test date formatting Sub TestFormatDates() Dim msg As String msg = String.Format("Current Date Time is {0:f}", Now()) Console.WriteLine(msg) ' => Current Date Time is Sunday, March 04, 2001 3:54 PM msg = String.Format("Current year is {0:yyyy}", Now()) Console.WriteLine(msg) ' => Current year is 2001 ' Format a date in the format mm/dd/yyyy, regardless of current locale. msg = String.Format("{0:MM\/dd\/yyyy}", Now()) Console.WriteLine(msg) ' => 03/04/2001 End Sub ' This procedure demonstrates that an object can change the way it reacts when ' passed to a Console.Write method, by overriding the ToString method Sub TestFormatToString() Dim msg As String Dim p As New PointXY(12.4, 5.6) msg = String.Format("First point is {0}", p) Console.WriteLine(msg) ' => First point is (12.4,5.6) End Sub ' this procedure tests the IFormattable interface Sub TestIFormattable() Dim msg As String msg = String.Format("First point is {0:[X-Y]}", New PointXY2(1, 5)) Console.WriteLine(msg) End Sub ' this procedure tests the IFormatProvider and ICustomFormatter interfaces Sub TestIFormatProvider() ' Prepare an array of arguments (25 inches and 5.2 feet). Dim args() As Object = {25, 5.1} ' Note that we create an instance of MetricConverter on the fly. Console.WriteLine(String.Format(New MetricConverter(), _ "Width is {0:in}, Height is {1:fe} meters", args)) ' => Width is 0.635, Height is 1.683 meters End Sub ' this procedure tests how to use IFormatter and a CultureInfo object Sub TestIFormatProvider2() ' Create a CultureInfo object for French-Canadian Dim ci As New System.Globalization.CultureInfo("fr-CA") ' This is the amount to be format as Canadian money (dollars). Dim amount As Double = 12345.6 Dim msg As String = String.Format(ci, "{0:C}", amount) Console.WriteLine(msg) ' => 12 345.60 $ End Sub ' this procedure tests a few shared methods of the Char data type Sub TestChar() ' Check an individual Char value. Console.WriteLine(Char.IsDigit("1"c)) ' => True ' Check the N-th character in a string. Console.WriteLine(Char.IsDigit("A123", 0)) ' => False End Sub ' this procedure tests the StringBuilder object Sub TestStringBuilder() ' Create a StringBuilder object with capacity of 1000 characters. Dim sb As New System.Text.StringBuilder(1000) ' Create a comma-delimited list of the first 100 integers. Dim n As Integer For n = 1 To 100 ' Note that two Append methods are faster than a single Append ' whose argument is the concatenation of N and ",". sb.Append(n) sb.Append(",") Next ' insert a string at the beginning of the buffer sb.Insert(0, "List of numbers: ") Console.WriteLine(sb) ' => List of numbers: 1,2,3,4,5,6,... ' display length of the current string Console.WriteLine("Length is " & sb.Length.ToString) ' => 309 ' Show how to use a StringBuilder to receive a value from an API call. ' Get the path of the windows directory Dim tmpPath As New System.Text.StringBuilder(256) Dim length As Integer = GetTempPath(tmpPath.Capacity, tmpPath) tmpPath.Length = length Console.WriteLine("Windows Temp Directory: {0}", tmpPath.ToString) End Sub Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Integer, ByVal lpBuffer As System.Text.StringBuilder) As Integer ' this procedure compares performance of String ans StringBuilder classes Sub TestStringBuilderVsStrings() Dim i As Integer Dim s As String Dim dt As DateTime Const TIMES As Integer = 10000 Console.WriteLine(TIMES.ToString & " iterations.") Console.Write("Appending to a regular string: ") dt = Date.Now For i = 1 To TIMES s &= CStr(i) & "," Next Console.WriteLine(Now.Subtract(dt).ToString & " secs.") Console.Write("Appending to a StringBuilder: ") dt = Date.Now Dim sb As New System.Text.StringBuilder(TIMES * 4) For i = 1 To TIMES sb.Append(CStr(i)) sb.Append(",") Next Console.WriteLine(Now.Subtract(dt).ToString & " secs.") End Sub ' this procedure demonstrates how to use the ToString method and ' other members of numeric classes Sub TestNumberClasses() ' Convert an integer to hexadecimal. Console.WriteLine(1234.ToString("X")) ' => 4D2 ' Display PI with 6 digits (in all). Dim d As Double = Math.PI Console.WriteLine(d.ToString("G6")) ' => 3.14159 Dim sngValue As Single = 1.23 ' Compare the Single variable sngValue with 1. ' Note that you must force the argument to Single. Select Case sngValue.CompareTo(CSng(1)) Case 1 Console.WriteLine("sngValue is > 1") Case 0 Console.WriteLine("sngValue is = 1") Case -1 Console.WriteLine("sngValue is < 1") End Select ' Display the highest value you can store in a Double variable. Console.WriteLine(Double.MaxValue) ' => 1.7976931348623157E308 ' the smallest positive numbers that can be stored in a Single or Double variable Console.WriteLine(Single.Epsilon) ' => 1.401298E-45 Console.WriteLine(Double.Epsilon) ' => 4.94065645841247E-324 ' Any number divided by infinity gives zero. Console.WriteLine(1 / Double.PositiveInfinity) ' => 0 End Sub ' this procedure tests the formatting of numbers Sub TestNumberFormatting() Dim intValue As Integer = 12345 Console.WriteLine(intValue.ToString("##,##0.00", Nothing)) ' => 12,345.00 ' this code requires the following Imports ' Imports System.Globalization ' create a readable NumberFormatInfo object which is initialized ' with attributes from the current locale Dim nfi As NumberFormatInfo = CType(NumberFormatInfo.CurrentInfo.Clone, NumberFormatInfo) ' NFI is a read-write object, so we can change its properties. nfi.NumberDecimalSeparator = "," nfi.NumberGroupSeparator = " " ' We can now format a value with our custom NumberFormatInfo object. Dim sngValue As Single = 12345.5 Console.WriteLine(sngValue.ToString("##,##0.00", nfi)) ' => 12 345,50 End Sub ' this procedure tests the parsing of numerical values Sub TestNumberParsing() ' Next line assigns 1234 to the variable. Dim shoValue As Short = Short.Parse("1234") Console.WriteLine(shoValue) ' => 1234 Dim dblValue As Double = Double.Parse(" 1,234.56E6 ", NumberStyles.Any) Console.WriteLine(dblValue) ' => 1234560000 Dim style As NumberStyles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowLeadingSign ' This works and assigns û123.45 to dblValue. Dim sngValue As Single = Single.Parse("-123.45", style) Console.WriteLine(sngValue) ' => -123.45 ' This throws a FormatException, because of the thousand separator. Try sngValue = Single.Parse("12,345.67", style) Catch ex As Exception Console.WriteLine("An exception has occurred") End Try ' Allow a thousand separator, but you decide what a thousand separator can be. Dim nfi As NumberFormatInfo = _ CType(NumberFormatInfo.CurrentInfo.Clone, NumberFormatInfo) ' Use a period to group digits, and a comma as a decimal separator nfi.NumberGroupSeparator = "." nfi.NumberDecimalSeparator = "," ' Parse a string using the specified separators. dblValue = Double.Parse("12345,56", NumberStyles.Any, nfi) Console.WriteLine(dblValue) End Sub ' this procedure tests the Convert class Sub TestConvertClass() ' Use a NumberFormatInfo object to convert a string into a Double. Dim nfi As NumberFormatInfo = _ CType(NumberFormatInfo.CurrentInfo.Clone, NumberFormatInfo) ' Use a period to group digits, and a comma as a decimal separator nfi.NumberGroupSeparator = "." nfi.NumberDecimalSeparator = "," ' Parse a string using the specified separators. Dim dblValue As Double = Convert.ToDouble("12.345,56", nfi) Console.WriteLine(dblValue) ' => 12345.56 End Sub ' this procedure tests Base64 conversions Sub TestBase64Conversions() ' an array of 16 bytes (two identical sequances of 8 bytes) Dim b() As Byte = {12, 45, 213, 88, 11, 220, 34, 0, 12, 45, 213, 88, 11, 220, 34, 0} ' convert it to a base64 string (for UU-encoding) Dim s64 As String = Convert.ToBase64String(b) Console.WriteLine(s64) ' convert it back to an array of bytes Dim b2() As Byte = Convert.FromBase64String(s64) ' check that the two arrays are equal Dim i As Integer Dim different As Boolean For i = 0 To b.GetUpperBound(0) Console.Write(b2(i).ToString & " ") If b(i) <> b2(i) Then different = True Next Console.WriteLine("") If different Then Console.WriteLine("The base-64 string wasn't converted back correctly") Else Console.WriteLine("The base-64 string was converted back correctly") End If End Sub ' this procedure tests random number generation Sub TestRandom() ' You need these conversions because the Ticks property ' returns a 64-bit value that must be truncated to a 32-bit integer. Dim rand As New Random(CInt(Date.Now.Ticks And Integer.MaxValue)) ' display 10 random integer values. Dim i As Integer For i = 1 To 10 Console.WriteLine(rand.Next) Next ' Get a value in the range 0 to 1000. Dim intValue As Integer = rand.Next(1000) Console.WriteLine(intValue) ' Get a value in the range 100 to 1000. intValue = rand.Next(100, 1000) ' get a floating point value in the range 0-1 Dim dblValue As Double = rand.NextDouble Console.WriteLine(dblValue) ' Get an array of 100 random byte values. Dim buffer(100) As Byte rand.NextBytes(buffer) Dim b As Byte For Each b In buffer Console.Write(b.ToString & " ") Next End Sub ' this procedure tests date and time methods Sub TestDateTime() ' Create a Date value by providing year, month, and day values. Dim dt1 As Date = New Date(2001, 3, 6) ' March 6, 2001 Console.WriteLine(dt1) ' Provides also hour, minute, and second values. Dim dt2 As Date = New Date(2001, 3, 6, 18, 30, 20) ' March 6, 2001 6:30:20 PM Console.WriteLine(dt2) ' Add millisecond value (half a second in this example). Dim dt3 As Date = New Date(2001, 3, 6, 18, 30, 20, 500) Console.WriteLine(dt3) ' Create a time value from ticks (10 million ticks = 1 second) Dim ticks As Long = 20000000 ' 2 seconds ' This is considered the time elapsed from Jan 1, 0001. Dim dt4 As Date = New Date(ticks) ' 1/1/0001 12:00:02 AM Console.WriteLine(dt4) ' The Now property returns the system date and time. Dim dt5 As Date = Date.Now ' e.g. October 21, 2001 3:22:30 PM Console.WriteLine(dt5) ' The Today property returns the system date only. Dim dt6 As Date = Date.Today ' e.g. October 21, 2001 0:00:00 AM Console.WriteLine(dt6) ' Is today the first day of the current month? If Date.Today.Day = 1 Then Console.WriteLine("First day of month") ' How many days have passed since January 1? Console.WriteLine(Date.Today.DayOfYear) ' Get current time û note that ticks are included. Console.WriteLine(Date.Now.TimeOfDay) ' => 10:39:28.3063680 ' Tomorrow's date Console.WriteLine(Date.Today.AddDays(1)) ' Yesterday's date Console.WriteLine(Date.Today.AddDays(-1)) ' What time will it be 2 hours and 30 minutes from now? Console.WriteLine(Date.Now.AddHours(2.5)) ' A CPU-intensive way to pause for 2 seconds. Dim endTime As Date = Date.Now.AddSeconds(2) Do : Loop Until Date.Now > endTime ' TimeSpan constructors ' One Long value is interpreted as a Ticks value. Dim ts1 As TimeSpan = New TimeSpan(13500000) ' 1.35 seconds Console.WriteLine(ts1) ' Three Integer values are interpreted as hours, minutes, seconds. Dim ts2 As TimeSpan = New TimeSpan(0, 32, 20) ' 32 minutes, 20 seconds Console.WriteLine(ts2) ' Four Integer values are interpreted as days, hours, minutes, seconds. Dim ts3 As TimeSpan = New TimeSpan(1, 12, 0, 0) ' 1 day and a half Console.WriteLine(ts3) ' (Note that arguments aren't checked for out-of-range errors, therefore ' the next statement delivers the same result as the previous one.) Dim ts4 As TimeSpan = New TimeSpan(0, 36, 0, 0) ' 1 day and a half Console.WriteLine(ts4) ' A fifth argument is interpreted as a millisecond value. Dim ts5 As TimeSpan = New TimeSpan(0, 0, 1, 30, 500) ' 90 seconds and a half Console.WriteLine(ts5) ' What will be the time 2 days, 10 hours, and 30 minutes from now? Console.WriteLine(Date.Now.Add(New TimeSpan(2, 10, 30, 0))) ' What was the time 1 day, 12 hours, and 20 minutes ago? Console.WriteLine(Date.Now.Subtract(New TimeSpan(1, 12, 20, 0))) ' How many days, hours, minutes, and seconds have elapsed ' since the beginning of the third millennium ? Dim startDate As New Date(2001, 1, 1) Dim ts As TimeSpan = Date.Now.Subtract(startDate) Console.WriteLine(ts) ' => 206.11:11:35.4627792 (may vary, of course) ' Is current date later than October 30, 2001 ? Select Case Date.Today.CompareTo(New Date(2001, 10, 30)) Case 1 ' later than Oct 30, 2001 Console.WriteLine("Later than Oct 30, 2001") Case -1 ' earlier than Oct 30, 2001 Console.WriteLine("Earlier than Oct 30, 2001") Case 0 ' Today is Oct 30, 2001 Console.WriteLine("Today is Oct 30, 2001") End Select ' Test for a leap year. Console.WriteLine(Date.IsLeapYear(2000)) ' => True ' Retrieve number of days in a given month. Console.WriteLine(Date.DaysInMonth(2000, 2)) ' => 29 End Sub ' this procedure tests date formats Sub TestDateFormats() ' This is March 6, 2001 6:18:20.500 PM û US East Coast time. Dim dt As Date = New Date(2001, 3, 6, 18, 30, 20, 500) Console.WriteLine(dt.ToShortDateString) ' => 03/06/2001 Console.WriteLine(dt.ToLongDateString) ' => Tuesday, March 06, 2001 Console.WriteLine(dt.ToShortTimeString) ' => 6:30 PM Console.WriteLine(dt.ToLongTimeString) ' => 6:30:20 PM Console.WriteLine(dt.ToFileTime) ' => 126283734205000000 Console.WriteLine(dt.ToOADate) ' => 36956.7710706019 Console.WriteLine(dt.ToUniversalTime) ' => 3/6/2001 11:30:20 PM Console.WriteLine(dt.ToLocalTime) ' => 3/6/2001 1:30:20 PM End Sub ' this procedure tests date parsing Sub TestDateParsing() Dim dt As Date = Date.Parse("2001/3/6 12:20:30") Console.WriteLine(dt) ' => 3/6/2001 12:20:30 PM ' Get a writeable copy of the current locale's DateTimeFormatInfo object. Dim dtfi As DateTimeFormatInfo dtfi = CType(DateTimeFormatInfo.CurrentInfo.Clone, DateTimeFormatInfo) ' Change date and time separators. dtfi.DateSeparator = "-" dtfi.TimeSeparator = "." ' Now we're ready to parse a date formatted in a non-standard way. Dim dt2 As Date = Date.Parse("2001-3-6 12.20.30", dtfi) Console.WriteLine(dt2) ' => 3/6/2001 12:20:30 PM ' Prepare to parse (dd/mm/yy) dates, in short or long format. dtfi.ShortDatePattern = "d/M/yyyy" dtfi.LongDatePattern = "dddd, dd MMMM, yyyy" ' Both dt3 and dt4 are assigned the date "March 6, 2001". Dim dt3 As Date = Date.Parse("6-3-2001", dtfi) Console.WriteLine(dt3) ' => 3/6/2001 12:00:00 AM Dim dt4 As Date = Date.Parse("Tuesday, 6 March, 2001", dtfi) Console.WriteLine(dt4) ' => 3/6/2001 12:00:00 AM ' Print the abbreviated names of months. Dim s As String For Each s In DateTimeFormatInfo.CurrentInfo.AbbreviatedMonthNames Console.WriteLine(s) Next ' dt5 is assigned the date "March 6, 2001". Dim dt5 As Date = Date.ParseExact("6-3-2001", "d-M-yyyy", Nothing) Console.WriteLine(dt5) ' => 3/6/2001 12:00:00 AM End Sub ' this procedure tests the TimeZone object Sub TestTimeZone() ' Get the TimeZone object for current time zone. Dim tz As TimeZone = TimeZone.CurrentTimeZone ' Display name of time zone, without and with daylight time. ' (I got this results by running this code in Italy.) Console.WriteLine(tz.StandardName) ' => W. Europe Standard Time Console.WriteLine(tz.DaylightName) ' => W. Europe Daylight Time ' Time offset of W.Europe time zone in March, when no daylight time is active. Console.WriteLine(tz.GetUtcOffset(New Date(2001, 3, 1))) ' => 01:00:00 ' Time offset of W.Europe time zone in July, when daylight time is active. Console.WriteLine(tz.GetUtcOffset(New Date(2001, 7, 1))) ' => 02:00:00 ' Daylight time in July. Console.WriteLine(tz.IsDaylightSavingTime(New Date(2001, 7, 1))) ' => True ' Retrieve the DaylightTime object for year 2001 for Italy. Dim dlc As System.Globalization.DaylightTime = tz.GetDaylightChanges(2001) Console.WriteLine("Starts at " & dlc.Start) ' => Starts at 3/25/2001 2:00:00 AM Console.WriteLine("Ends at " & dlc.End) ' => Ends at 10/28/2001 3:00:00 AM ' Delta returns a TimeSpan object Console.WriteLine("Delta is " & dlc.Delta.TotalMinutes.ToString & " minutes.") ' => Delta is 60 minutes. End Sub ' this procedure tests the GUID type Sub TestGuid() ' create a new GUID Dim guid1 As Guid = Guid.NewGuid ' By definition, you'll surely get a different output here. Console.WriteLine("New GUID: " & guid1.ToString) '=> New GUID: 3f5f1d42-2d92-474d-a2a4-1e707c7e2a37 ' initialize from a string. Dim guid2 As New Guid("45FA3B49-3D66-AB33-BB21-1E3B447A6621") ' Convert to an array of bytes. Dim bytes() As Byte = guid1.ToByteArray Dim b As Byte For Each b In bytes Console.Write(b.ToString & " ") Next Console.WriteLine("") ' Compare two GUIDs. If guid1.Equals(guid2) Then Console.WriteLine("GUIDs are equal.") Else Console.WriteLine("GUIDs are different.") End If End Sub ' this procedure tests various Enum behaviors Sub TestEnum() Dim de As DataEntry = DataEntry.DateTime ' Display the numeric value. Console.WriteLine(de) ' => 3 ' Display the symbolic value. Console.WriteLine(de.ToString) ' => DateTime ' Show the value in hexadecimal format with four digits. Console.WriteLine(de.ToString("X")) ' => 0003 ' You can use the GetType method (inherited from System.Object) ' to get the Type object required by the Parse method. de = CType([Enum].Parse(de.GetType, "CharString"), DataEntry) ' Print the enum value corresponding to CharString Console.WriteLine(de) ' => 2 ' *** This statement throws an exception. Try de = CType([Enum].Parse(de.GetType, "charstring"), DataEntry) Catch ex As Exception Console.WriteLine(ex.Message) End Try ' This works well, because case-insensitive comparison is used. de = CType([Enum].Parse(de.GetType, "charstring", True), DataEntry) Console.WriteLine(de) ' The GetUnderlying method Console.WriteLine([Enum].GetUnderlyingType(de.GetType)) ' => System.Int16 ' NOTE: it is important that the second argoment of IsDefined ' be the same type as the underlying type of the Enum (Short in this case) If [Enum].IsDefined(GetType(DataEntry), 3S) Then ' 3 is a valid value for the DataEntry class. de = CType(3, DataEntry) Console.WriteLine(de.ToString) ' DateTime End If ' This code produces an invalid result, yet it doesn't throw an exception. de = CType(123, DataEntry) ' Another way to check whether an enum value is valid ' (doesn't require strict type matching ,as IsDefined does) If [Enum].GetName(GetType(DataEntry), 3) <> "" Then de = CType(3, DataEntry) End If Console.WriteLine("") ' List all the values in DataEntry. Dim names() As String = [Enum].GetNames(GetType(DataEntry)) Dim values As Array = [Enum].GetValues(GetType(DataEntry)) Dim i As Integer For i = 0 To names.Length - 1 Console.WriteLine("{0} = {1}", names(i), CInt(values.GetValue(i))) Next End Sub ' this procedure tests bitcoded Enums Sub TestEnumFlags() Dim vde As ValidDataEntry vde = ValidDataEntry.IntegerNumber Or ValidDataEntry.DateTime Console.WriteLine(vde.ToString) ' => IntegerNumber, DateTime Dim vde2 As ValidDataEntry Console.WriteLine(vde2.ToString) ' => None vde = CType(123, ValidDataEntry) Console.WriteLine(vde.ToString) ' => 123 vde = CType([Enum].Parse( _ vde.GetType, "IntegerNumber, FloatingNumber"), ValidDataEntry) Console.Write(CInt(vde)) ' => 3 End Sub End Module